<?php
class giic extends CI_Controller {
	public function index(){
		$this->load->view('gii');
	}
	public function make(){
		/**************************生成控制器文件******************************************/
		//根据模板复制控制器
		$dbname=$this->input->post('dbname');
		$str=file_get_contents('./application/controllers/gii_template/controller.php');
		$str=str_replace('dbname', $dbname, $str);
		/*根据表结构构建验证规则，查询字段*/
		$fields=$this->db->query('SHOW FULL FIELDS FROM ci_'.$dbname)->result('array');
		/*循环字段，拼凑验证规则*/
		$rules=array();
		foreach ($fields as $v) {
			if($v['Field']=='id'){
				continue;
			}
			if($v['Null']==='NO' && $v['Default']===''){
				$rules[]='$this->form_validation->set_rules(\''.$v['Field'].'\',\''.$v['Comment'].'\',\'required\');';
			}
		}
		/*替换规则*/
		if($rules){
			$str=str_replace('#_form_rules;', implode("\r\n\t\t", $rules), $str);
		}
		/*写入文件*/
		file_put_contents('./application/controllers/admin/'.$dbname.'c.php', $str);
		echo "控制器代码生成完毕，保存在'./application/controllers/admin/{$dbname}c.php'目录下<br><hr>";
		/***************************生成模型文件*******************************************/
		// 或者不用file_get_contents('');用：
		ob_start();
		include('./application/controllers/gii_template/model.php');
		$str=ob_get_clean();
		//生成文件
		file_put_contents('./application/models/'.$dbname.'m.php', "<?php\r\n".$str);
		echo "模型代码生成完毕，保存在'./application/models/{$dbname}m.php'目录下<br><hr>";
		/******************************生成模板文件**********************************/
		$viewdir="./application/views/admin/".$dbname;
		if(!is_dir($viewdir)){
			/*创建文件*/
			mkdir($viewdir,0777,TRUE);
		}
		/*生成add.php*/
		ob_start();
		include('./application/controllers/gii_template/add.php');
		$str=ob_get_clean();
		//生成文件
		file_put_contents($viewdir.'/add.php', $str);
		echo "添加数据页面代码生成完毕，保存在'$viewdir/add.php'目录下<br><hr>";
		/*生成list.php*/
		ob_start();
		include('./application/controllers/gii_template/list.php');
		$str=ob_get_clean();
		//生成文件
		file_put_contents($viewdir.'/list.php', $str);
		echo "管理数据页面代码生成完毕，保存在'$viewdir/list.php'目录下<br><hr>";
		/*生成save.php*/
		ob_start();
		include('./application/controllers/gii_template/save.php');
		$str=ob_get_clean();
		//生成文件
		file_put_contents($viewdir.'/save.php', $str);
		echo "修改数据页面代码生成完毕，保存在'$viewdir/save.php'目录下<br><hr>";
		echo "代码生成完毕！";
	 }
}